#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: 高建平
# @description: 
#
import json
import time
from fastapi import FastAPI, HTTPException, Request,Response,status
from fastapi.responses import JSONResponse
from loguru import logger
from app.exceptions.status import Status
from app.models.result import  Result


def middleware(app:FastAPI):
    
    async def set_body(request: Request):
        receive_ = await request._receive()
        async def receive():
            return receive_
        request._receive = receive
        return receive_


    @app.middleware("http")
    async def logging(request: Request, call_next):
        """
        获取request body
        """
        try:
            start_time = time.time()
            query_param = {}
            body = {}
            if request.method == 'GET':
                query_param = request.query_params._dict
            dict = await set_body(request)
            if dict['body'] and len(dict['body']) > 0:
                body = await request.json()
            response = await call_next(request)
        # except Exception as exc:
            # logger.exception(exc)
            # response = JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,content=Result(code=Status.HTTP_FAIL.code, message='系统异常').__dict__)
            # raise exc
        finally:
            cost_time = int(round((time.time() - start_time) * 1000))
            logger.info("url={} cost_time={}ms header={} params={} body={} " ,request.url.path,cost_time,request.headers,query_param,body)
        return response